#define _CRT_SECURE_NO_WARNINGS
#include "Queue.h"


void QueueInit(Queue* q)
{
	assert(q);

	q->phead = NULL;
	q->ptail = NULL;
	q->size = 0;
}


void QueuePush(Queue* q, QDataType x)
{
	assert(q);

	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return;
	}
	newnode->next = NULL;
	newnode->x = x;

	if (q->size == 0)
	{
		q->phead = q->ptail = newnode;
	}
	else
	{
		q->ptail->next = newnode;
		q->ptail = newnode;
	}
	q->size++;
}


void QueuePop(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	
	if (q->phead->next == NULL)
	{
		free(q->ptail);
		q->phead = q->ptail = NULL;
	}
	else
	{
		QNode* pheadNext = q->phead->next;
		free(q->phead);
		q->phead = pheadNext;
	}
	q->size--;
}


QDataType QueueFront(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->phead->x;
}


QDataType QueueBack(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->ptail->x;
}


int QueueSize(Queue* q)
{
	assert(q);

	return q->size;
}


bool QueueEmpty(Queue* q)
{
	assert(q);

	return q->size == 0;
}


void QueueDestroy(Queue* q)
{
	assert(q);

	QNode* cur = q->phead;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	q->phead = q->ptail = NULL;
	q->size = 0;
}

